<template>
	<view class="page-group">
		<view class="title-group-view">
			<text @click="changeTabClick(0)" :class="currentTab===0?'title-tab-native':'title-tab-normal'">二维码授权</text>
			<text @click="changeTabClick(1)" :class="currentTab===1?'title-tab-native':'title-tab-normal'">登录授权</text>
		</view>	
		<view class="center-group-view" v-if="currentTab===0">
			<text class="center-top-txt">请使用另一部手机进行扫码授权</text>
			<view class="input-box-view" style="margin-top: 42rpx;">
				<text class="input-tip-view">打开抖音扫一扫，完成授权</text>
				<view style="position: relative;width: 360rpx;height: 360rpx;">
					<image class="input-qrcode" :src="qrCodeUrl.replace(/[\r\n]/g,'')"></image>
					<view class="smegma-view" v-if="isExpire">二维码已失效</view>
				</view>
				<text class="time-text" @click="refreshClick()">{{countdown}}<text v-show="timestatus">s后过期</text></text>
				<view @click="saveQrcodeClick()" class="save-qrcode-btn" :style="isExpire?'background: #999999;':'background: linear-gradient(138deg, #F7CB47 0%, #C2CF51 100%);'">保存二维码</view>
			</view>
		</view>
		<view class="input-box-view" style="margin-top: 80rpx;" v-else>
			<text class="input-tip-view" style="margin-top: 94rpx;color: #FF5733;">复制链接使用电脑浏览器打开</text>
			<text class="input-tip-view" style="margin-top: 24rpx;color: #333333;">登录账号完成授权</text>
			<view @click="copyLinkClick()" class="save-qrcode-btn" style="margin-top: 76rpx;margin-bottom: 82rpx;background: linear-gradient(138deg, #F7CB47 0%, #C2CF51 100%);" >复制链接</view>
		</view>
		<view class="bottom-group-view">
			<text>授权后：</text>
			<view style="display: flex;align-items: center;margin-top: 22rpx;">
				<image src="/static/mine/icon_selected.png"/>
				<text>同步账号基础信息以及查看账号运营数据</text>
			</view>
			<view style="display: flex;align-items: center;margin-top: 18rpx;">
				<image src="/static/mine/icon_selected.png"/>
				<text>获得联盟售卖的订单数据</text>
			</view>
		</view>
	</view>
</template>

<script>
	import configUrls from '@/common/config.js';
	export default {
		data() {
			return {
				currentTab: 0,
				qrcodeBase64: "",
				qrCodeUrl: "",
				qrcodeIndexUrl: "",
				timestatus: false,
				countdown: '刷新',
				clear:'',
				isExpire: false,
				token: '',
				isRefreshQuery: false,
			}
		},
		onLoad(options) {
			this.getOauthConnect();
		},
		onUnload() {
			console.log('000>>>>')
			//离开页面 不用刷新了
			this.isRefreshQuery = false
		},
		methods: {
			getOauthQuery() {
				var that = this;
				this.$Request.postJson(configUrls.getOauthQuery, {
					code: that.token,
				}).then(res => {
					if (res.code == "10000"){
						const status = res.data.status;
						if (status == "confirmed") {
							that.isRefreshQuery = false;
							uni.showModal({
								content: '恭喜您授权确认已通过',
								showCancel: false,
								success() {
									uni.navigateBack({
										delta:1,
									})
								}
							})
						}
					}else{
						// uni.showToast({
						// 	icon:'none',
						// 	title:'正在查询授权结果,请等待...',
						// 	duration: 2000
						// })
					}
					if(that.isRefreshQuery) { //三秒后轮训一次
						setTimeout(()=>{
							this.getOauthQuery();
						},1000)
					}
				});
			},
			getOauthConnect() {
				let that = this;
				this.$Request.postJsonLoadView(configUrls.getOauthConnect, {
				}).then(res => {
					if (res.code == "10000") {
						that.token = res.data.token;
						that.qrcodeBase64 = res.data.qrcode;
						that.qrCodeUrl = "data:image/png;base64,"+res.data.qrcode;
						that.qrcodeIndexUrl = res.data.qrcodeIndexUrl;
						that.countdown = 60;
						that.timestatus = true;
						that.isExpire = false;
						that.isRefreshQuery = true;
						that.getOauthQuery();
						that.clear = setInterval(that.countDown, 1000);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}); 
			},
			// 倒计时
			countDown(){
			    var that = this;
			    if(!that.countdown){
					that.isExpire = true;                     
			        that.timestatus = false;
					that.isRefreshQuery = false;
			        that.countdown = '刷新';
			        clearInterval(that.clear);
			    }else{
			        --that.countdown;
			    }
			},
			copyLinkClick() {
				uni.setClipboardData({
					data: this.qrcodeIndexUrl,
					success: function () {
					    uni.showToast({
					        title: "复制成功",
					        icon: 'none',
							duration: 2000
					    });
					}
				});
			},
			changeTabClick(index) {
				this.currentTab = index;
			},
			refreshClick() {
				if (this.isExpire) {
					this.getOauthConnect();
				}
			},
			saveBase64ImageToPhotosAlbum() {
				let that = this
				var timestamp = new Date().getTime();
				let base64 = this.qrcodeBase64;//.replace(/^data:image\/\w+;BASE64,/, ""); //去掉data:image/png;base64,
				let filePath = wx.env.USER_DATA_PATH + `/addFriends_${timestamp}_qrcode.png`;
				uni.showLoading({
					title: '保存中',
					mask: true
				})
				uni.getFileSystemManager().writeFile({
					filePath: filePath, //创建一个临时文件名
					data: base64, //写入的文本或二进制数据
					encoding: 'base64', //写入当前文件的字符编码
					success: res => {
						uni.saveImageToPhotosAlbum({
							filePath: filePath,
							success: function(res2) {
								uni.hideLoading();
								uni.showToast({
									title: "保存成功",
									icon: 'none',
									duration: 2000
								});
							},
							fail: function(err) {
								uni.hideLoading();
								console.log(err.errMsg);
								uni.showToast({
									title: "保存失败",
									icon: 'none',
									duration: 2000
								});
							}
						})
					},
					fail: err => {
						uni.hideLoading();
						console.log(err)
						uni.showToast({
							title: "创建文件失败",
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			saveQrcodeClick() {//保存图片到相册按钮的点击事件函数
				if (this.isExpire) {
					return;
				}
				let that = this
				uni.getSetting({
					success(res) {
						console.log(res);
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success(res) {
								that.saveBase64ImageToPhotosAlbum()
							},
							fail() {
								uni.showModal({
									content: '请允许相册权限,拒绝将无法正常保存图片',
									showCancel: false,
									success() {
										uni.openSetting({
											success(settingdata) {
												if (settingdata.authSetting['scope.writePhotosAlbum']) {} else {
													console.log('获取权限失败')
													uni.showToast({
														title: "获取权限失败",
														icon: 'none',
														duration: 2000
													});
												}
											}
										})
									}
								})
							}
						})
						} else {
							that.saveBase64ImageToPhotosAlbum()
						}
					}
				})
			},
		}
	}
</script>

<style>
	@import url("../../css/mine/empower.css");
</style>